<template>
  <el-row :class="prefixCls" :gutter="20" justify="space-between">
    <el-col :lg="6" :md="12" :sm="12" :xl="6" :xs="24">
      <el-card class="mb-20px" shadow="hover">
        <el-skeleton :loading="loading" :rows="2" animated>
          <template #default>
            <div :class="`${prefixCls}__item flex justify-between`">
              <div>
                <div :class="`${prefixCls}__item--icon ${prefixCls}__item--peoples p-16px inline-block rounded-6px`">
                  <Icon :size="40" icon="svg-icon:peoples" />
                </div>
              </div>
              <div class="flex flex-col justify-between">
                <div :class="`${prefixCls}__item--text text-16px text-gray-500 text-right`">{{ t('analysis.newUser') }}
                </div>
                <CountTo :duration="2600" :end-val="totalState.users" :start-val="0"
                  class="text-right text-20px font-700" />
              </div>
            </div>
          </template>
        </el-skeleton>
      </el-card>
    </el-col>

    <el-col :lg="6" :md="12" :sm="12" :xl="6" :xs="24">
      <el-card class="mb-20px" shadow="hover">
        <el-skeleton :loading="loading" :rows="2" animated>
          <template #default>
            <div :class="`${prefixCls}__item flex justify-between`">
              <div>
                <div :class="`${prefixCls}__item--icon ${prefixCls}__item--message p-16px inline-block rounded-6px`">
                  <Icon :size="40" icon="svg-icon:peoples" />
                </div>
              </div>
              <div class="flex flex-col justify-between">
                <div :class="`${prefixCls}__item--text text-16px text-gray-500 text-right`">{{
    t('analysis.unreadInformation') }}
                </div>
                <CountTo :duration="2600" :end-val="totalState.messages" :start-val="0"
                  class="text-right text-20px font-700" />
              </div>
            </div>
          </template>
        </el-skeleton>
      </el-card>
    </el-col>

    <el-col :lg="6" :md="12" :sm="12" :xl="6" :xs="24">
      <el-card class="mb-20px" shadow="hover">
        <el-skeleton :loading="loading" :rows="2" animated>
          <template #default>
            <div :class="`${prefixCls}__item flex justify-between`">
              <div>
                <div :class="`${prefixCls}__item--icon ${prefixCls}__item--money p-16px inline-block rounded-6px`">
                  <Icon :size="40" icon="svg-icon:shopping" />
                </div>
              </div>
              <div class="flex flex-col justify-between">
                <div :class="`${prefixCls}__item--text text-16px text-gray-500 text-right`">{{
    t('analysis.transactionAmount') }}
                </div>
                <CountTo :duration="2600" :end-val="totalState.shoppings" :start-val="0"
                  class="text-right text-20px font-700" />
              </div>
            </div>
          </template>
        </el-skeleton>
      </el-card>
    </el-col>

    <el-col :lg="6" :md="12" :sm="12" :xl="6" :xs="24">
      <el-card class="mb-20px" shadow="hover">
        <el-skeleton :loading="loading" :rows="2" animated>
          <template #default>
            <div :class="`${prefixCls}__item flex justify-between`">
              <div>
                <div :class="`${prefixCls}__item--icon ${prefixCls}__item--shopping p-16px inline-block rounded-6px`">
                  <Icon :size="40" icon="svg-icon:money" />
                </div>
              </div>
              <div class="flex flex-col justify-between">
                <div :class="`${prefixCls}__item--text text-16px text-gray-500 text-right`">{{
    t('analysis.totalShopping') }}
                </div>
                <CountTo :duration="2600" :end-val="totalState.moneys" :start-val="0"
                  class="text-right text-20px font-700" />
              </div>
            </div>
          </template>
        </el-skeleton>
      </el-card>
    </el-col>
  </el-row>
  <el-row :gutter="20" justify="space-between">
    <el-col :lg="10" :md="24" :sm="24" :xl="10" :xs="24">
      <el-card class="mb-20px" shadow="hover">
        <el-skeleton :loading="loading" animated>
          <Echart :height="300" :options="pieOptionsData" />
        </el-skeleton>
      </el-card>
    </el-col>
    <el-col :lg="14" :md="24" :sm="24" :xl="14" :xs="24">
      <el-card class="mb-20px" shadow="hover">
        <el-skeleton :loading="loading" animated>
          <Echart :height="300" :options="barOptionsData" />
        </el-skeleton>
      </el-card>
    </el-col>
    <el-col :span="24">
      <el-card class="mb-20px" shadow="hover">
        <el-skeleton :loading="loading" :rows="4" animated>
          <Echart :height="350" :options="lineOptionsData" />
        </el-skeleton>
      </el-card>
    </el-col>
  </el-row>
</template>
<script lang="ts" setup>
import { set } from 'lodash-es'
import { EChartsOption } from 'echarts'

import { useDesign } from '@/hooks/web/useDesign'
import { agentAPI } from '@/api/index/index'
import type { AnalysisTotalTypes } from './types'
import {lineOptions } from './echarts-data'
defineOptions({ name: 'Home2' })

const { t } = useI18n()
const loading = ref(true)
const { getPrefixCls } = useDesign()
const prefixCls = getPrefixCls('panel')

let totalState = reactive<AnalysisTotalTypes>({
  users: 0,
  messages: 0,
  moneys: 0,
  shoppings: 0
})
let piepotionsMsg = ref([])

const getCount = async () => {
  const dataList = await agentAPI.getCountMemberAndProxys()
  const data = {
    users: dataList.members,
    messages: dataList.proxys,
    moneys: (dataList.moneys / 100).toFixed(2),
    shoppings: dataList.packageOrders
  }
  totalState = Object.assign(totalState, data)
}

const pieOptionsData = reactive(
  {
    title: {
      text: t('analysis.userAccessSource'),
      top: 'bottom'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b} : {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: []
    },
    // legend: {
    //   top: 'buttom'
    // },
    toolbox: {
      show: true,
      feature: {
        mark: { show: true },
        dataView: { show: true, readOnly: false,optionToContent: function () {
            // 这里可以自定义数据视图中显示的内容
            let axisData = piepotionsMsg;
            var table = '<table style="width:100%;color:#111;text-align: center"><tbody><tr><td>会员地址</td><td>会员数量</td></tr>';
            for (var i = 0, l = axisData.length; i < l; i++) {
                table += '<tr><td>' + axisData[i].name + '</td><td>' + axisData[i].value + '</td></tr>';
            }
            table += '</tbody></table>';  
            return table;
        }},
        restore: { show: true },
        saveAsImage: { show: true }
      }
    },
    series: [
      {
        name: t('analysis.userAccessSource'),
        type: 'pie',
        center: '60%',
        data: []
      }
    ]
  }
)
// 会员地区分布
const getUserAccessSource = async () => {
  let dataList = await agentAPI.getCountPackageOrders()
  piepotionsMsg = dataList
  if (dataList.length > 5) {
  // 取前5个元素
  let firstFive = dataList.slice(0, 10);
  // 从第6个元素开始累加value值
  let otherValue = dataList.slice(10).reduce((sum, item) => sum + item.value, 0);
  // 创建一个新的元素表示'其它'
  let otherItem = { value: otherValue, name: '其它' };
  // 替换原数组
  dataList = firstFive.concat(otherItem);
}
  const data = dataList
  pieOptionsData.legend.data = data.map((v) => t(v.name))
  pieOptionsData.series[0].data = data
}

// 套餐销售额
const barOptionsData = reactive ({
  title: {
    text: t('analysis.weeklyUserActivity'),
    left: 'center'
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  grid: {
    left: 50,
    right: 20,
    bottom: 20
  },
  xAxis: {
    type: 'category',
    data: [],
    axisTick: {
      alignWithLabel: true
    }
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: t('analysis.activeQuantity'),
      data: [],
      type: 'bar'
    }
  ]
})
const getCountMemberAreas = async () => {
  let dataList = await agentAPI.getCountMemberAreas()
  barOptionsData.xAxis.data = dataList.packageList
  barOptionsData.series[0].data = dataList.numList
}
// 周活跃量
const getWeeklyUserActivity = async () => {
  const data = [
    { value: 13253, name: 'analysis.monday' },
    { value: 34235, name: 'analysis.tuesday' },
    { value: 26321, name: 'analysis.wednesday' },
    { value: 12340, name: 'analysis.thursday' },
    { value: 24643, name: 'analysis.friday' },
    { value: 1322, name: 'analysis.saturday' },
    { value: 1324, name: 'analysis.sunday' }
  ]
  set(
    barOptionsData,
    'xAxis.data',
    data.map((v) => t(v.name))
  )
  set(barOptionsData, 'series', [
    {
      name: t('analysis.activeQuantity'),
      data: data.map((v) => v.value),
      type: 'bar'
    }
  ])
}

const lineOptionsData = reactive<EChartsOption>(lineOptions) as EChartsOption

// 每月销售总额
const getMonthlySales = async () => {
  const dataList = await agentAPI.getCountMonthOrders()
  const functionList = dataList.functionList
  const monthList = dataList.monthList
  const packageList = dataList.packageList
  set(
    lineOptionsData,
    'xAxis.data',
    monthList
  )
  set(lineOptionsData, 'series', [
    {
      name: t('analysis.estimate'),
      smooth: true,
      type: 'line',
      data: functionList,
      animationDuration: 2800,
      animationEasing: 'cubicInOut'
    },
    {
      name: t('analysis.actual'),
      smooth: true,
      type: 'line',
      itemStyle: {},
      data: packageList,
      animationDuration: 2800,
      animationEasing: 'quadraticOut'
    }
  ])
}

const getAllApi = async () => {
  await Promise.all([getCount(), getUserAccessSource(), getWeeklyUserActivity(), getMonthlySales()])
  loading.value = false
}

getAllApi()
onMounted(() => {
  getCount()
  getUserAccessSource()
  getCountMemberAreas()
  getMonthlySales()
})
</script>

<style lang="scss" scoped>
$prefix-cls: #{$namespace}-panel;

.#{$prefix-cls} {
  &__item {
    &--peoples {
      color: #40c9c6;
    }

    &--message {
      color: #36a3f7;
    }

    &--money {
      color: #f4516c;
    }

    &--shopping {
      color: #34bfa3;
    }

    &:hover {
      :deep(.#{$namespace}-icon) {
        color: #fff !important;
      }

      .#{$prefix-cls}__item--icon {
        transition: all 0.38s ease-out;
      }

      .#{$prefix-cls}__item--peoples {
        background: #40c9c6;
      }

      .#{$prefix-cls}__item--message {
        background: #36a3f7;
      }

      .#{$prefix-cls}__item--money {
        background: #f4516c;
      }

      .#{$prefix-cls}__item--shopping {
        background: #34bfa3;
      }
    }
  }
}
</style>
